/**
 * @filename:DirectoryInfoServiceImpl 2025-04-27
 * @project starhub-schema  V1.0
 */
package com.starhub.engine.directory.service.impl;

import com.starhub.engine.directory.entity.DirectoryTreeSelect;
import com.starhub.engine.directory.entity.TreeBuild;
import com.starhub.engine.directory.entity.TreeSelectBuild;
import com.starhub.engine.directory.request.DirectoryShareBsRequest;
import com.starhub.engine.directory.result.*;
import com.starhub.engine.document.dao.DocumentShareDao;
import com.starhub.engine.document.entity.DocumentShare;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.engine.directory.entity.DirectoryInfo;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.directory.dao.DirectoryInfoDao;
import com.starhub.engine.directory.service.DirectoryInfoService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

/**   
 * @Description:(附件目录管理服务实现)
 *
 * @version: V1.0
 * @author: 孙赛赛-sss
 * 
 */
@Service
public class DirectoryInfoServiceImpl implements DirectoryInfoService {

    private static final Logger log = LoggerFactory.getLogger(DirectoryInfoServiceImpl.class);
    @Autowired
    private DirectoryInfoDao directoryDao;

    @Autowired
    private DocumentShareDao documentShareDao;

    /**
    * 新增
    * @param user
    * @param directory
    * @return
    */
    public DirectoryDealResult addDirectoryInfo(LoginUser user, DirectoryInfo directory){
        Long userId = Long.parseLong(user.getUserId());
        //判断用户是否有文件夹的创建权限
        List<DocumentShare> documentShares = documentShareDao.getDirectoryShareById(directory.getParentId(),userId);
        boolean permission = false;
        for(DocumentShare documentShare:documentShares){
            if(documentShare.getPermission()==6||documentShare.getPermission()==3){
                permission = true;
            }
        }
        if(!permission){//具有新建或者完全控制权限
            return DirectoryDealResult.fail("当前登录用户没有新建目录权限");
        }
        Long id = IdGenerator.generateId();

        //数据封装，默认值添加
        directory.setId(id);
        directory.setUserId(userId);
        directory.setCreateDateTime(new Date());
        directory.setCreateDateTime(new Date());

        int add = directoryDao.insertSelective(directory);
        //目录权限继承
        documentShares = documentShareDao.getDirectoriesById(directory.getParentId());
        for(DocumentShare share:documentShares){
            DocumentShare newShare = new DocumentShare();
            newShare.setId(IdGenerator.generateId());
            newShare.setDirectoryId(id);
            newShare.setPermission(share.getPermission());
            newShare.setUserId(share.getUserId());
            newShare.setCreateDateTime(new Date());
            documentShareDao.insert(newShare);
        }
        log.info("目录创建结果==={}",add>0?"目录创建成功":"目录创建失败");
        return DirectoryDealResult.success(String.valueOf(id));
    }

    /**
    * 更新
    * @param user
    * @param directory
    * @return
    */
    public DirectoryDealResult updateDirectoryInfo(LoginUser user, DirectoryInfo directory){
        Long userId = Long.parseLong(user.getUserId());
        //判断用户是否有文件夹的创建权限
        List<DocumentShare> documentShares = documentShareDao.getDirectoryShareById(directory.getId(),userId);
        boolean permissionF = false;
        for(DocumentShare documentShare:documentShares){
            if(documentShare.getPermission()==7||documentShare.getPermission()==3){
                permissionF = true;
            }
        }
        if(!permissionF){//具有新建或者完全控制权限
            log.info("{}==当前登录用户没有编辑权限",userId);
            return DirectoryDealResult.fail("当前登录用户没有编辑权限");
        }
        //查询当前的父级目录，一致的话，目录权限不做处理
        DirectoryInfo directoryInfo = directoryDao.selectByPrimaryKey(directory.getId());
        Long parentId = directory.getParentId();
        if(directoryInfo!=null){
            parentId = directoryInfo.getParentId();
        }
        IdGenerator idGenerator = new IdGenerator(1, 1);
        if(parentId!=directory.getParentId()){
            //按照更新后的父级目录进行更新菜单权限
            documentShares = documentShareDao.getDirectoriesById(directory.getParentId());
            //先将全部相关权限删除
            documentShareDao.deleteDocumentShareByFileDirId(null,directoryInfo.getId());
            for(DocumentShare share:documentShares){
                DocumentShare newShare = new DocumentShare();
                newShare.setId(idGenerator.generate());
                newShare.setDirectoryId(directory.getId());
                newShare.setPermission(share.getPermission());
                newShare.setUserId(share.getUserId());
                newShare.setCreateDateTime(new Date());
                documentShareDao.insert(newShare);
            }
        }
        //不允许更新的属性设置为null
        directory.setDirectoryPath(null);
        directory.setUserId(null);
        directory.setCreateDateTime(null);
        int edit = directoryDao.updateByPrimaryKeySelective(directory);
        log.info("更新结果==={}",edit>0?"目录编辑成功":"目录编辑失败");
        return DirectoryDealResult.success(String.valueOf(directory.getId()));
    }

    /**
    * 基本信息获取
    * @param user
    * @param id
    * @return
    */
    public DirectoryDealResult getDirectoryInfoInfo(LoginUser user, Long id){
        Long userId = Long.parseLong(user.getUserId());
        DirectoryInfo directoryInfo = directoryDao.selectByUserPrimaryKey(id,userId);
        if(directoryInfo==null){
            return DirectoryDealResult.fail("目录不存在");
        }
        return DirectoryDealResult.success(String.valueOf(id),directoryInfo);
    }

    /**
    * 根据id删除，此方法为物理删除
    * @param user
    * @param ids
    */
    public DirectoryDealResult deleteDirectoryInfoRecord(LoginUser user, String ids){
        Long userId = Long.parseLong(user.getUserId());
        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
                .map((id) -> Long.parseLong(id))
                .collect(Collectors.toList());
        List<DocumentShare> documentShares = documentShareDao.getDirectorySharesById(idList,userId);
        List<Long> permissionList = new ArrayList<>();
        for(DocumentShare documentShare:documentShares){
            if(documentShare.getPermission()==3||documentShare.getPermission()==10){//完全控制或者删除权限
                permissionList.add(documentShare.getDirectoryId());
            }
        }
        directoryDao.deleteDirectoryInfoRecord(permissionList);
        for(Long directoryId:permissionList){//删除文件夹的共享权限
            documentShareDao.deleteDocumentShareByFileDirId(null,directoryId);
        }
        return DirectoryDealResult.success(ids);
    }

    /**
    * 列表查询
    * @param user
    * @param params
    */
    public DirectoryDealListResult getDirectoryInfoList(LoginUser user, Map<String , Object>  params){
        Long userId = Long.parseLong(user.getUserId());
        Long parentId = params.get("parentId")!=null?(Long) params.get("parentId"):0L;
        List<DirectoryInfo> directoryList =  getChildrenDirectory(params,userId);
        List<DirectoryInfo> tempList = new ArrayList<>();
        for(DirectoryInfo directoryInfo:directoryList){
            DirectoryInfo temp = new DirectoryInfo();
            temp.setChildren(new ArrayList<>());
            temp.setDirectoryPath(directoryInfo.getDirectoryPath());
            temp.setId(directoryInfo.getId());
            temp.setUserId(directoryInfo.getUserId());
            temp.setCreateDateTime(directoryInfo.getCreateDateTime());
            temp.setName(directoryInfo.getName());
            temp.setParentId(directoryInfo.getParentId());
            tempList.add(temp);
        }
        TreeBuild treeBuild = new TreeBuild(tempList,parentId);

        tempList = treeBuild.buildTree();
        return DirectoryDealListResult.success(tempList,tempList.size());
    }

    @Override
    public DirectoryDealListResult getDirectoryInfoNormalList(LoginUser user, Map<String, Object> params) {
        Long userId = Long.parseLong(user.getUserId());
        List<DirectoryInfo> directoryList =  getChildrenDirectory(params,userId);
        List<DirectoryInfo> tempList = new ArrayList<>();
        for(DirectoryInfo directoryInfo:directoryList){
            DirectoryInfo temp = new DirectoryInfo();
            temp.setChildren(new ArrayList<>());
            temp.setDirectoryPath(directoryInfo.getDirectoryPath());
            temp.setId(directoryInfo.getId());
            temp.setUserId(directoryInfo.getUserId());
            temp.setCreateDateTime(directoryInfo.getCreateDateTime());
            temp.setName(directoryInfo.getName());
            temp.setParentId(directoryInfo.getParentId());
            tempList.add(temp);
        }
        return DirectoryDealListResult.success(tempList,tempList.size());
    }

    @Override
    public DirectoryDealTreeResult getDirectoryTreeSeletList(LoginUser user, Map<String, Object> params) {
        Long userId = Long.parseLong(user.getUserId());
        Long parentId = params.get("parentId")!=null?(Long) params.get("parentId"):0L;
        List<DirectoryInfo> directoryList =  getChildrenDirectory(params,userId);
        List<DirectoryTreeSelect> tempList = new ArrayList<>();
        for(DirectoryInfo directoryInfo:directoryList){
            DirectoryTreeSelect temp = new DirectoryTreeSelect();
            temp.setChildren(new ArrayList<>());
            temp.setValue(directoryInfo.getId());
            temp.setTitle(directoryInfo.getName());
            temp.setParentId(directoryInfo.getParentId());
            tempList.add(temp);
        }
        TreeSelectBuild treeBuild = new TreeSelectBuild(tempList,parentId);
        return DirectoryDealTreeResult.success(treeBuild.buildTree(),tempList.size());
    }

    @Override
    public DirectoryShareDealListResult getDirectoryShareList(Long directoryId, LoginUser user) {
        Long userId = Long.parseLong(user.getUserId());
        List<DocumentShare> documentShares = documentShareDao.getDirectoryShareById(directoryId,userId);
        return DirectoryShareDealListResult.success(documentShares,documentShares.size());
    }

    @Override
    public DirectoryShareDealListResult getDirectoryShareList(Long directoryId) {
        List<DocumentShare> documentShares = documentShareDao.getDirectoriesById(directoryId);
        return DirectoryShareDealListResult.success(documentShares,documentShares.size());
    }

    @Override
    public DirectoryShareDealResult grantDirectoryUserShare(DirectoryShareBsRequest directoryShareBsRequest, LoginUser user) {
        String userIds = directoryShareBsRequest.getUserIds();
        String permissionIds = directoryShareBsRequest.getPermissionIds();
        Long directoryId = directoryShareBsRequest.getDirectoryId();
        String[] userIdArr = StringUtils.split(userIds, ",");
        String[] permissionArr = StringUtils.split(permissionIds, ",");
        IdGenerator idGenerator = new IdGenerator(1, 1);
        //新增时需要将父子目录的权限也新增
        for (String userId : userIdArr) {
            for (String permissionId : permissionArr) {
                DocumentShare exists = documentShareDao.checkPermissionByDirUserId(directoryId,Long.parseLong(userId),Integer.parseInt(permissionId));
                if(exists==null){
                    DocumentShare documentShare = new DocumentShare();
                    documentShare.setId(idGenerator.generate());
                    documentShare.setDirectoryId(directoryId);
                    documentShare.setUserId(Long.parseLong(userId));
                    documentShare.setPermission(Integer.parseInt(permissionId));
                    documentShare.setCreateDateTime(new Date());
                    documentShareDao.insert(documentShare);
                }
            }
        }
        return DirectoryShareDealResult.success("权限保存成功");
    }

    @Override
    public DirectoryShareDealResult delDirectoryUserShare(DirectoryShareBsRequest directoryShareBsRequest, LoginUser user) {
        String userIds = directoryShareBsRequest.getUserIds();
        String permissionIds = directoryShareBsRequest.getPermissionIds();
        Long directoryId = directoryShareBsRequest.getDirectoryId();
        String[] userIdArr = StringUtils.split(userIds, ",");
        String[] permissionArr = StringUtils.split(permissionIds, ",");
        //删除时需要将父子目录的权限也删除
        for (String userId : userIdArr) {
            if("".equals(userId))continue;
            for (String permissionId : permissionArr) {
                if("".equals(permissionId))continue;
                documentShareDao.deleteDirectoryShare(Long.parseLong(userId),Integer.parseInt(permissionId),directoryId);
            }
        }
        return DirectoryShareDealResult.success("权限删除成功");
    }


    public List<DirectoryInfo> getChildrenDirectory(Map<String , Object> params,Long userId){
        Long parentId = (Long)params.get("parentId");
        List<DirectoryInfo> directoryList =  directoryDao.selectByParams(params,userId);
        List<DirectoryInfo> totalList = new ArrayList<>();
        for(DirectoryInfo directoryInfo:directoryList){
            params.replace("parentId",directoryInfo.getId());
            List<DirectoryInfo> newList = getChildrenDirectory(params,userId);
            if(!newList.isEmpty()){
                totalList.addAll(newList);
            }
            totalList.add(directoryInfo);
        }
        return  totalList;
    }


}